package project.jsf;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import project.entity.Revisor;
import project.jsf.util.JsfUtil;
import project.jsf.util.PaginationHelper;
import project.ejbs.RevisorFacade;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import project.ejbs.EmailFacade;
import project.ejbs.RevisaoFacade;
import project.ejbs.Session;
import project.ejbs.SubmissaoFacade;
import project.entity.Papel;
import project.entity.Revisao;
import project.entity.RevisaoKey;
import project.entity.Submissao;

@ManagedBean(name = "revisorController")
@SessionScoped
public class RevisorController implements Serializable {

    private Revisor current;
    private DataModel items = null;
    @EJB
    private project.ejbs.RevisorFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @EJB
    private Session sessao;
    @EJB
    private RevisaoFacade ejbRevisao;
    @EJB
    private SubmissaoFacade ejbSubmissao;
    @EJB
    private EmailFacade ejbEmail;
    private String submissao;
    private String procura = "";
    private String tipoProcuraSelecionada = "Username";
    private String[] tipoProcura = {"Username", "Primeiro Nome", "Ultimo Nome", "E-Mail", "Empresa"};
    private DataModel revisores;
    private String confirmarPassword;

    public RevisorController() {
    }

    public Revisor getSelected() {
        if (current == null) {
            current = new Revisor();
            selectedItemIndex = -1;
        }
        return current;
    }

    private RevisorFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    try {
                        if (tipoProcuraSelecionada.equals(tipoProcura[0])){
                            return getFacade().countUsername((procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao()));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[1])){
                            return getFacade().countPNome((procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao()));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[2])){
                            return getFacade().countUNome((procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao()));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[3])){
                            return getFacade().countEmail((procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao()));
                        }
                        return getFacade().countEmpresa((procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao()));
                    } catch (Exception e) {
                        return 0;
                    }
                }

                @Override
                public DataModel createPageDataModel() {
                    try {
                        if (tipoProcuraSelecionada.equals(tipoProcura[0])){
                            return new ListDataModel(getFacade().searchUsername(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, (procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao())));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[1])){
                            return new ListDataModel(getFacade().searchPNome(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, (procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao())));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[2])){
                            return new ListDataModel(getFacade().searchUNome(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, (procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao())));
                        } else if (tipoProcuraSelecionada.equals(tipoProcura[3])){
                            return new ListDataModel(getFacade().searchEmail(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, (procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao())));
                        }
                        return new ListDataModel(getFacade().searchEmpresa(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, (procura + "%"), ejbSubmissao.find(sessao.getIdSubmissao())));
                    } catch (Exception e) {
                        return new ListDataModel();
                    }
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Revisor) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Revisor();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            
            if (!current.getEmail().matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")){
                JsfUtil.addErrorMessage("E-Mail com formato inválido.");
                return null;
            }
            if (current.getDataNascimento().after(new Date())){
                JsfUtil.addErrorMessage("Data de nascimento inválida! (dd/mm/yyyy)");
                return null;
            }
            if(current.getPassword().equals(confirmarPassword) && !current.getPassword().equals("")){
                current.setPasswordHash(current.getPassword());
                current.setPapel(new Papel(current, Papel.Perfil.Revisor));
                current.setDataRegisto(new Date());
                current.setEliminado(false);
                getFacade().create(current);
                JsfUtil.addSuccessMessage("Conta registada com sucesso.");
                return "/evento/List";
            }
            
            if (current.getPassword().equals(""))
                JsfUtil.addErrorMessage("O campo da password não pode estar vazio.");
            else
                JsfUtil.addErrorMessage("A confirmação de password está errada.");
            
            return null;
            
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Ocurreu um erro ao tentar registar. Verifique o username.");
            return null;
        }
    }

    public String prepareEdit() {
        current = (Revisor) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
        revisores = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the procura
     */
    public String getProcura() {
        return procura;
    }

    /**
     * @param procura the procura to set
     */
    public void setProcura(String procura) {
        this.procura = procura;
    }

    /**
     * @return the tipoProcuraSelecionada
     */
    public String getTipoProcuraSelecionada() {
        return tipoProcuraSelecionada;
    }

    /**
     * @param tipoProcuraSelecionada the tipoProcuraSelecionada to set
     */
    public void setTipoProcuraSelecionada(String tipoProcuraSelecionada) {
        this.tipoProcuraSelecionada = tipoProcuraSelecionada;
    }

    /**
     * @return the tipoProcura
     */
    public String[] getTipoProcura() {
        return tipoProcura;
    }
    
    public String adicionarRevisor(){
        current = (Revisor) getItems().getRowData();
        Revisao rev = new Revisao();
        rev.setRevisor(current);
        Submissao sub = ejbSubmissao.find(sessao.getIdSubmissao());
        rev.setSubmissao(sub);
        ejbRevisao.create(rev);
        current.getRevisoes().add(rev);
        ejbFacade.edit(current);
        sub.getRevisoes().add(rev);
        ejbSubmissao.edit(sub);
        
        try {
            ejbEmail.enviar(current.getEmail() , "Nova Revisao", "Caro/a " + current.getpNome() + " " + current.getuNome() + ",\nUma nova submissao esta pronta para revisao.\n\nObrigado.");
        } catch (MessagingException ex) {
            Logger.getLogger(RevisorController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        recreateModel();
        return "List";
    }

    public String retirarRevisor(){
        //Obter Revisor
        current = (Revisor) getRevisores().getRowData();
        
        //Obter Revisao & Eliminar
        Revisao rev = ejbRevisao.find(new RevisaoKey(current.getUsername(), sessao.getIdSubmissao()));
        
        //Eliminar do Revisor
        int i = 0;
        for (Iterator it = current.getRevisoes().iterator(); it.hasNext();) {
            Revisao object = (Revisao) it.next();
            if (object.getRevisor().getUsername().equals(current.getUsername())){
                ((List)current.getRevisoes()).remove(i);
                break;
            }
            i++;
        }
        
        ejbFacade.edit(current);
        
        //Eliminar da Submissao
        Submissao sub = ejbSubmissao.find(sessao.getIdSubmissao());
        i = 0;
        for (Iterator it = sub.getRevisoes().iterator(); it.hasNext();) {
            Revisao object = (Revisao) it.next();
            if (object.getSubmissao().getIdSubmissao().equals(sub.getIdSubmissao())){
                ((List)sub.getRevisoes()).remove(i);
                break;
            }
            i++;
        }
        ejbSubmissao.edit(sub);
        
        //Eliminar
        ejbRevisao.remove(rev);
        
        recreateModel();
        return "List";
    }
    
    /**
     * @return the revisores
     */
    public DataModel getRevisores() {
        if (revisores == null) {
            revisores = createPageDataModel();
        }
        return revisores;
    }

    private DataModel createPageDataModel() {
        //TODO: Fazer consulta à tabela Revisão
        try {
            return new ListDataModel(ejbRevisao.searchRevisorSubmissao(sessao.getIdSubmissao()));
        } catch (Exception e) {
            return new ListDataModel();
        }
        
    }

    /**
     * @return the submissao
     */
    public String getSubmissao() {
        try{
            return ejbSubmissao.find(sessao.getIdSubmissao()).getTitulo();
        } catch(Exception e) {
            return "";
        }
    }
    
    public String prepareRevisores(DataModel submissoes){
        sessao.setIdSubmissao(((Submissao) submissoes.getRowData()).getIdSubmissao());
        recreateModel();
        return "/revisor/List";
    }
    
    public boolean isStarted(String username){
        Revisao rev = ejbRevisao.find(new RevisaoKey(username, sessao.getIdSubmissao()));
        return rev.getEstado() == 0;
    }

    /**
     * @return the confirmarPassword
     */
    public String getConfirmarPassword() {
        return confirmarPassword;
    }

    /**
     * @param confirmarPassword the confirmarPassword to set
     */
    public void setConfirmarPassword(String confirmarPassword) {
        this.confirmarPassword = confirmarPassword;
    }

    @FacesConverter(forClass = Revisor.class)
    public static class RevisorControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            RevisorController controller = (RevisorController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "revisorController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Revisor) {
                Revisor o = (Revisor) object;
                return getStringKey(o.getUsername());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + RevisorController.class.getName());
            }
        }
    }
}
